package com.wpp;

import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public class ConnectionTest {
//
//    @Test
//    public void connectionTest() throws SQLException {
//        Driver driver = new Driver("com.mysql.cj.jdbc.Driver");
//
//        String url = "jdbc:mysql://localhost:3306/books";
//        Properties properties = new Properties();
//        properties.setProperty("user","root");
//        properties.setProperty("password","wpy581");
//
//
//        driver.connect(url,properties);
//
//    }

    @Test
    public void connectionTestTwo() throws Exception {

        /*
         * 连接数据库的方式三
         * ps:jar包导依赖
         * */
        Class cls = Class.forName("com.mysql.cj.jdbc.Driver");
        Driver driver = (Driver) cls.newInstance();
        DriverManager.registerDriver(driver);

        String url = "jdbc:mysql://localhost:3306/books?serverTimezone=GMT";
        String user = "root";
        String password = "wpy581";

        Connection connection = DriverManager.getConnection(url, user, password);
        System.out.println(connection);
    }

    @Test
    public void connectionTestThree() throws Exception {
        /*
         * 连接数据库的方式四
         * 只是加载驱动，不用显示的注册驱动
         * */


        String url = "jdbc:mysql://localhost:3306/books?serverTimezone=GMT";
        String user = "root";
        String password = "wpy581";

        //加载驱动
        Class.forName("com.mysql.cj.jdbc.Driver");
        /*
        为什么可以省略上述操作呢？
            在mysql的Driver实现类中，声明了静态代码块
                static {
        try {
            DriverManager.registerDriver(new Driver());
        } catch (SQLException var1) {
            throw new RuntimeException("Can't register driver!");
        }
    }
        */


        Connection connection = DriverManager.getConnection(url, user, password);
        System.out.println(connection);
    }


    @Test
    public void connectionTestFour() throws Exception {
        /*
         * 连接数据库的方式五：将数据库连接的基本信息，声明在配置文件中，通过读取配置文件的方式，获取连接
         * 配置文件放在src下
         * 优点：不需要在代码中改配置。移值性好，实现了解耦
         *
         *
         * */

        //获取配置信息
        //加载进流
        InputStream resourceAsStream = ConnectionTest.class.getClassLoader().getResourceAsStream("jdbc.properties");
        Properties properties = new Properties();
        properties.load(resourceAsStream);

        //读取属性
        String user = properties.getProperty("user");
        String password = properties.getProperty("password");
        String url = properties.getProperty("url");
        String driver = properties.getProperty("driver");

        Class.forName(driver);


        Connection connection = DriverManager.getConnection(url, user, password);
        System.out.println(connection);

    }


}
